package com.ihr360.payroll.service.payslip.impl;

import com.ihr360.authority.sharing.annonation.AccessControl;
import com.ihr360.authority.sharing.model.ResourceAccess;
import com.ihr360.commons.context.session.Ihr360SessionContextHolder;
import com.ihr360.commons.exception.Ihr360Exception;
import com.ihr360.commons.lang.CollectionUtils;
import com.ihr360.payroll.config.PayslipConfigEntity;
import com.ihr360.payroll.dao.PayslipConfigRepository;
import com.ihr360.payroll.dao.SalaryPlanRepository;
import com.ihr360.payroll.model.dto.salary.plan.SalaryPlan;
import com.ihr360.payroll.model.dto.salary.plan.config.PayslipConfig;
import com.ihr360.payroll.service.payslip.PayslipConfigService;
import com.ihr360.payroll.service.salaryplan.SalaryPlanService;
import com.ihr360.rest.reposity.SimpleRestReposity;
import com.ihr360.rest.service.AbstractSimpleRestServiceImpl;
import com.ihr360.validation.ValidationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@AccessControl(disableAll = true)
public class PayslipConfigServiceImpl extends AbstractSimpleRestServiceImpl<PayslipConfig, Long> implements PayslipConfigService {

    @Autowired
    PayslipConfigRepository payslipConfigRepository;
    @Autowired
    SalaryPlanRepository salaryPlanRepository;
    @Autowired
    SalaryPlanService salaryPlanService;


    @Override
    public SimpleRestReposity<PayslipConfig, Long> getSimpleRestReposity() {
        return payslipConfigRepository;
    }

    @Override
    public List<PayslipConfigEntity> getList(String companyId) {
        List<PayslipConfigEntity> result = new ArrayList<>();
        List<SalaryPlan> salaryPlanList = (List<SalaryPlan>) salaryPlanService.getAllInCompany();
        if (CollectionUtils.isEmpty(salaryPlanList)) {
            return result;
        }
        for (SalaryPlan salaryPlan : salaryPlanList) {
            if (CollectionUtils.isEmpty(salaryPlan.getPayslipConfigs())) {
                continue;
            }
            Long salaryPlanId = salaryPlan.getId();
            ResourceAccess resourceAccess = salaryPlan.getResourceAccess();
            salaryPlan.getPayslipConfigs().forEach(payslipConfig ->
                    result.add(new PayslipConfigEntity(payslipConfig.getId(), salaryPlanId, payslipConfig.isEnabled(),
                            payslipConfig.getName(), resourceAccess.getAccessPrivilege(), resourceAccess.getResourcePublicity()))
            );
        }
        return result;
    }

    @Override
    public List<PayslipConfig> getListBySalaryPlanId(Long salaryPlanId) {
        SalaryPlan salaryPlan = salaryPlanService.getOne(salaryPlanId);
        return salaryPlan.getPayslipConfigs();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PayslipConfig saveOrUpdate(PayslipConfig payslipConfig, Long salaryPlanId) {
        SalaryPlan salaryPlan = salaryPlanService.getOne(salaryPlanId);
        if (payslipConfig.getId() == null) {
            payslipConfig.setCreatedAt(new Date());
            payslipConfigRepository.save(payslipConfig);
            if (salaryPlan == null) {
                ValidationUtils.reject("", "没有找到对应方案！");
            }
            salaryPlan.getPayslipConfigs().add(payslipConfig);
            salaryPlanRepository.save(salaryPlan);
        } else {
            payslipConfig.setUpdatedAt(new Date());
            payslipConfigRepository.save(payslipConfig);
        }
        return payslipConfig;
    }

    @Override
    public boolean isDuplicateName(String name, Long id) {
        String companyId = Ihr360SessionContextHolder.getCompanyId();
        return id == null ? payslipConfigRepository.countByCompanyIdAndName(companyId, name) > 0
                : payslipConfigRepository.countByCompanyIdAndIdNotAndName(companyId, id, name) > 0;
    }

    @Override
    public boolean deletePayslipConfig(Long salaryPlanId, Long payslipConfigId) {
        SalaryPlan salaryPlan = salaryPlanService.getOne(salaryPlanId);
        PayslipConfig payslipConfig = super.getOne(payslipConfigId);
        if (payslipConfig.isDefaultPayslipConfig()) {
            ValidationUtils.reject("", "默认工资单，不允许删除！");
        }
        List<PayslipConfig> payslipConfigs = salaryPlan.getPayslipConfigs();
        PayslipConfig deletePayslipConfig = null;
        for (PayslipConfig config : payslipConfigs) {
            if (payslipConfigId.equals(payslipConfig.getId())) {
                deletePayslipConfig = config;
            }
        }
        if (deletePayslipConfig != null) {
            payslipConfigs.remove(deletePayslipConfig);
            salaryPlan.setPayslipConfigs(payslipConfigs);
            salaryPlanRepository.save(salaryPlan);
        }
        try {
            payslipConfigRepository.delete(payslipConfigId);
        } catch (DataIntegrityViolationException e) {
            throw new Ihr360Exception(null, "要删除的数据已被其他数据关联，无法删除");
        } catch (Exception e) {
            throw new Ihr360Exception(null, "无法删除数据，请刷新后重试");
        }
        return false;
    }


}
